package pb

import (
	"os"

	mysqlproxy "gitee.com/xuender/mysql-proxy"
	"github.com/pelletier/go-toml"
	"github.com/xuender/oils/base"
	"github.com/xuender/oils/cryptos"
)

func NewConfig(config string) *Config {
	file := base.Panic1(os.Open(config))
	defer file.Close()

	ret := &Config{}
	decoder := toml.NewDecoder(file)
	base.Panic(decoder.Decode(ret))
	ret.Path = file.Name()

	return ret
}

func (p *Config) GetConnByID(connID uint32) *Conn {
	for _, conn := range p.Conns {
		if conn.Id == connID {
			return conn
		}
	}

	return nil
}

// Check 配置文件检查.
func (p *Config) Check() error {
	nameSet := base.NewSet[string]()
	for _, conn := range p.Conns {
		nameSet.Add(conn.Name)

		userSet := base.NewSet[string]()
		for _, user := range conn.Users {
			userSet.Add(user.User)
		}

		if len(userSet) != len(conn.Users) {
			return ErrUserName
		}
	}

	if len(nameSet) != len(p.Conns) {
		return ErrConnName
	}

	return nil
}

func (p *Config) Save(config string) error {
	if config == "" {
		config = p.Path
	}

	for _, conn := range p.Conns {
		if !cryptos.IsEncrypt(conn.Password) {
			conn.Password = cryptos.Encrypt(conn.Password, mysqlproxy.DefaultKey, cryptos.AES)
		}
	}

	for user, password := range p.Auth {
		if !cryptos.IsEncrypt(password) {
			p.Auth[user] = cryptos.Encrypt(password, mysqlproxy.DefaultKey, cryptos.AES)
		}
	}

	file := base.Panic1(os.Create(config))
	defer file.Close()

	encoder := toml.NewEncoder(file)

	return encoder.Encode(p)
}
